{extend name="app/admin/view/base.html"/}
{block name="resources"}
<style>
	.ns-form {margin-top: 0;}
	.coupon-box{
		padding: 20px;
	}

	.coupon-box .layui-form{
		padding: 0!important;
	}

	.layui-layer-page .layui-layer-content{
		overflow: auto !important;
	}

	.ns-del-btn {
		cursor: pointer;
	}
	.ns-level-equity .layui-input {
		display: inline-block;
	}
	.gods-box table:first-of-type{
		margin-bottom: 0;
	}
	.gods-box table:last-of-type{
		margin-top: 0;
		display: block;
		max-height: 323px;
		overflow: auto;
	}
	.coupon-box .ns-single-filter-box{
		padding-top: 0;
	}
	.align-center{
		text-align: center!important;
	}
	.colorSelector{
		position: relative;
	    width: 20px;
	    height: 20px;
	    border-radius: 3px;
	    border: 1px solid #d7d7d7;
	    display: inline-block;
    	cursor: pointer;
    	vertical-align: middle;
	    padding: 2px;
	}
	.colorSelector div{
		width: 100%;
		height: 100%;
		border-radius: 3px;
	}
	.flexbox-fix-btn .btn{
		margin-top: 0;
		line-height: 1;
	}
</style>
{/block}
{block name="main"}
<div class="layui-form">

	<div class="layui-card ns-card-common ns-card-brief">
		<div class="layui-card-header">
			<span class="ns-card-title">基础信息</span>
		</div>
		<div class="layui-card-body">

			<div class="layui-form-item">
				<label class="layui-form-label"><span class="required">*</span>会员卡名称：</label>
				<div class="layui-input-block">
					<input name="level_name" type="text" lay-verify="required" class="layui-input ns-len-long">
				</div>
			</div>

			<div class="layui-form-item">
				<label class="layui-form-label img-upload-lable">封面图：</label>
				<div class="layui-input-block img-upload">
					<div class="upload-img-block">
						<div class="upload-img-box">
							<div class="ns-upload-default" id="storeUpload">
								<div class="upload">
									<img src="SHOP_IMG/upload_img.png" />
									<p>点击上传</p>
								</div>

							</div>
							<div class="operation"  >
								<div >
									<i title="图片预览" class="iconfont iconreview js-preview" style="margin-right: 20px;"></i>
									<i title="删除图片" class="layui-icon layui-icon-delete js-delete"></i>
								</div>
								<div class="replace_img js-replace">点击替换</div>
							</div>
							<input type="hidden" name="cover">
						</div>
					</div>
				</div>
			</div>

			<div class="layui-form-item" hidden>
				<label class="layui-form-label">会员卡详情：</label>
				<div class="layui-input-block ns-special-length">
					<script id="container" name="detail" type="text/plain" style="width:800px;height:300px;"></script>
				</div>
			</div>



			<div class="layui-form-item">
				<label class="layui-form-label"><span class="required">*</span>会员卡金额：</label>
				<div class="layui-input-block">
					<input name="level_price" type="number" lay-verify="required|num" class="layui-input ns-len-long">
				</div>
			</div>

			<div class="layui-form-item" hidden>
				<label class="layui-form-label">会员卡封面背景色：</label>
				<div class="layui-input-block flex">
					<div class="flex_fill">
						<div class="picker colorSelector" id="color-picker">
							<div data-value="#333"></div>
						</div>
					</div>
				</div>
			</div>
			<div class="layui-form-item" hidden>
				<label class="layui-form-label"><span class="required">*</span>付费方式：</label>
				<div class="layui-input-block">
					<input type="radio" name="charge_type" value="0" title="付款" checked>
					<input type="radio" name="charge_type" value="1" title="充值">
				</div>
			</div>
			<div class="layui-form-item charge-rule" hidden>
				<label class="layui-form-label"><span class="required">*</span>付费规则：</label>
				<div class="layui-input-block">
					<table class="layui-table ns-len-long" lay-skin="nob" id="level-rule">
						<colgroup>
							<col width="30%">
							<col width="50%">
							<col width="20%">
						</colgroup>
						<thead>
							<tr>
								<th>有效期</th>
								<th class="align-center">价格</th>
<!--								<th class="align-center">划线价</th>-->
								<th>操作</th>
							</tr>
						</thead>
						<tbody>

						</tbody>
					</table>
					<a href="javascript:void(0)" class="ns-text-color" onclick="addRule()" id="add_rule_btn">添加规则</a>
				</div>
			</div>
		</div>
	</div>



	<div class="layui-card ns-card-common ns-card-brief ns-level-equity">
		<div class="layui-card-header">
			<span class="ns-card-title">权益</span>
		</div>
		<div class="layui-card-body">

			<div class="layui-form-item" hidden>
				<label class="layui-form-label">是否包邮：</label>
				<div class="layui-input-block">
					<input type="checkbox" name="is_free_shipping" value="1" lay-skin="switch" />
				</div>
			</div>

			<div class="layui-form-item">
				<label class="layui-form-label"><span class="required">*</span>消费折扣：</label>
				<div class="layui-input-block">
					<input type="number" name="consume_discount" value="100" min="0" max="100" lay-verify="fl" autocomplete="off" class="layui-input ns-len-short"> %
				</div>
			</div>

			<div class="layui-form-item" hidden>
				<label class="layui-form-label">积分回馈倍率：</label>
				<div class="layui-input-block">
					<input type="number" name="point_feedback" min="0" max="100" lay-verify="jf" autocomplete="off" class="layui-input ns-len-short"> 倍
				</div>
				<div class="ns-word-aux">回馈积分 = 消费金额 * 积分回馈倍率</div>
			</div>
		</div>
	</div>

	<div class="layui-card ns-card-common ns-card-brief" hidden>
		<div class="layui-card-header">
			<span class="ns-card-title">开卡礼包</span>
		</div>
		<div class="layui-card-body">

			<div class="layui-form-item" hidden>
				<label class="layui-form-label">赠送积分：</label>
				<div class="layui-input-block">
					<input name="send_point" type="number" lay-verify="num" min="0" class="layui-input ns-len-short">
				</div>
			</div>

			<div class="layui-form-item" hidden>
				<label class="layui-form-label">赠送红包：</label>
				<div class="layui-input-block ns-len-long">
					<input name="send_balance" type="number" lay-verify="num" min="0" class="layui-input ns-len-short">
				</div>
			</div>

			<div class="layui-form-item">
				<label class="layui-form-label">赠送优惠券：</label>
				<div class="layui-input-block coupon">
					<div class="discount-cont">
						<div><a href="javascript:;" class="ns-text-color select-coupon">选择优惠券</a></div>
						<div class="ns-word-aux" style="margin-left: 0">
							<p>请确认优惠券数量是否充足，优惠券数量不足将导致赠送失败</p>
						</div>
						<div>
							<table class="layui-table" lay-skin="nob">
								<colgroup>
									<col width="30%">
									<col width="50%">
									<col width="20%">
								</colgroup>
								<thead>
								<tr>
									<th>优惠券</th>
									<th>优惠内容</th>
									<th style="text-align:center;">操作</th>
								</tr>
								</thead>
								<tbody>

								</tbody>
							</table>
						</div>
					</div>
				</div>
			</div>

<!--			<div class="ns-word-aux">开卡礼包仅首次购卡发放</div>-->
		</div>
	</div>

	<div class="layui-card ns-card-common ns-card-brief ns-level-equity">
		<div class="layui-card-header">
			<span class="ns-card-title">权益描述</span>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">详情描述：</label>
			<!--<div class="layui-input-block ns-len-long">
				<textarea name="remark" class="layui-textarea"></textarea>
			</div>-->
			<div class="layui-input-inline">
				<script id="editor3" type="text/plain" class="ns-special-length" style="height:300px;"></script>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">一级内容描述：</label>
			<div class="layui-input-inline">
				<script id="editor" type="text/plain" class="ns-special-length" style="height:300px;"></script>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">二级内容描述：</label>
			<div class="layui-input-inline">
				<script id="editor2" type="text/plain" class="ns-special-length" style="height:300px;"></script>
			</div>
		</div>
	</div>

	<div class="layui-card ns-card-common">
		<div class="layui-card-body">
			<div class="ns-form-row">
				<button class="layui-btn ns-bg-color" lay-submit lay-filter="save">保存</button>
				<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
			</div>
		</div>
	</div>
</div>

<!-- 优惠券 -->
<script type="text/html" id="couponList">
	<div class="gift-box">
		<div class="ns-single-filter-box">
			<div class="layui-form">
				<div class="layui-input-inline">
					<input type="text" name="platformcoupon_name" placeholder="请输入优惠券名称" class="layui-input ns-len-mid">
					<button type="button" class="layui-btn layui-btn-primary" lay-filter="coupon-search" lay-submit>
						<i class="layui-icon">&#xe615;</i>
					</button>
				</div>
			</div>
		</div>
		<table id="coupon_list" lay-filter="coupon_list"></table>
	</div>
</script>

<!-- 优惠券-名称 -->
<script type="text/html" id="couponName">
	<div class="ns-table-tuwen-box">
		<div class="ns-font-box">
			<p class="ns-multi-line-hiding">{{d.platformcoupon_name}}</p>
		</div>
	</div>
</script>
<!-- 优惠券-操作 -->
<script type="text/html" id="couponOperation">
	{{# var select_coupon_list = ','+coupon_list+','}}
	{{# if(select_coupon_list.indexOf(','+d.platformcoupon_type_id+',') != -1){ }}
	<p title="该优惠券已参加">已添加</p>
	{{# }else{ }}
	<a class="layui-btn" lay-event="add">添加</a>
	{{# } }}
</script>
{/block}
{block name="script"}
<script type="text/javascript" charset="utf-8" src="STATIC_EXT/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="STATIC_EXT/ueditor/ueditor.all.js"></script>
<script type="text/javascript" charset="utf-8" src="STATIC_EXT/ueditor/lang/zh-cn/zh-cn.js"></script>
<script>
    var coupon_id = [], addCoupon;
	var coupon_list = '';
    var form;
	var laytpl;

	var ue = UE.getEditor('editor');

	var ue2 = UE.getEditor('editor2');

	var ue3 = UE.getEditor('editor3');
    layui.use(['form', 'laytpl'], function() {
        form = layui.form;
		laytpl = layui.laytpl,
            repeat_flag = false; //防重复标识
        form.render();


		var upload = new Upload({
			elem: '#storeUpload'
		});

        /**
         * 监听保存
         */
        form.on('submit(save)', function(data) {
        	data.field.bg_color = $('#color-picker').attr('data-value');

            data.field.send_coupon = coupon_id.toString();
            if (repeat_flag) return false;

			/*let level = {};
			$('#level-rule tr').each(function (i, e) {
				if($(e).find('.price').val() != undefined){

					level[$(e).find('select').val()] = $(e).find('.price').val();
				}
				/!*if($(e).find('.market_price').val() != undefined){
					level[$(e).find('select').val()] = $(e).find('.market_price').val();
				}*!/
			})
			if(JSON.stringify(level) == '{}'){
				layer.msg('请设置付费规则');
				return false;
			}

			data.field.charge_rule = JSON.stringify(level);*/

			if(!data.field.cover) upload.delete();

			data.field.first_content_description = ue.getContent();
			data.field.second_content_description = ue2.getContent();
			data.field.remark = ue3.getContent();
			data.field.send_coupon = coupon_list;
			repeat_flag = true;
			$.ajax({
                url: ns.url("supermember://admin/membercard/add"),
                data: data.field,
                dataType: 'JSON', //服务器返回json格式数据
                type: 'POST', //http请求类型
                success: function(res) {
                    repeat_flag = false;
                    if (res.code == 0) {
                        layer.confirm('添加成功', {
                            title:'操作提示',
                            btn: ['返回列表', '继续添加'],
							closeBtn: 0,
                            yes: function(){
                                location.href = ns.url("supermember://admin/membercard/lists")
                            },
                            btn2: function() {
                                location.href = ns.url("supermember://admin/membercard/add")
                            }
                        });
                    }else{
                        layer.msg(res.message);
                    }
                }
            });
        });
        
        /**
         * 表单验证
         */
        form.verify({
            num: function(value) {
                var arrmen = value.split(".");
                var val = 0;
                if (arrmen.length == 2) {
                    val = arrmen[1];
                }

                if (value == "") {
                    return false;
                }
                if (value < 0 || val.length > 2) {
                    return '请输入大于等于0的数，保留小数点后两位'
                }
            },
            fl: function(value, item) {
                var str = $(item).parents(".layui-form-item").find("label").text().split("*").join("");
                str = str.substring(0, str.length - 1);

            	if (isNaN(parseFloat(value))) {
                	return  "请设置" + str;
                }

                if (value <= 0) {
                    return str + "不能小于等于0";
                }

                if (value > 100) {
                    return str + "不能大于100";
                }

                var arrMen = value.split(".");
                var val = 0;
                if (arrMen.length == 2) {
                    val = arrMen[1];
                }
                if (val.length > 2) {
                    return str + "最多可保留两位小数";
                }
            },
            jf: function(value, item) {
                var str = $(item).parents(".layui-form-item").find("label").text().split("*").join("");
                str = str.substring(0, str.length - 1);

                if (value < 0) {
                    return str + "不能小于0";
                }

                if (value > 100) {
                    return str + "不能大于100";
                }

                var arrMen = value.split(".");
                var val = 0;
                if (arrMen.length == 2) {
                    val = arrMen[1];
                }
                if (val.length > 2) {
                    return str + "最多可保留两位小数";
                }
            }
        });

    });



    function back(){
        location.href = ns.url("supermember://admin/membercard/lists");
    }
	$('body').on('click', '.select-coupon', function(e){
		var event = this;

		layer.open({
			type: 1,
			area: ["950px","600px"],
			title: '优惠券列表',
			skin: 'select-coupon-layer',
			content: $("#couponList").html()
		});

		couponTable = new Table({
			elem: "#coupon_list",
			url: ns.url("platformcoupon://admin/platformcoupon/lists"),
			where: {'status': 1},
			cols: [
				[{
					title: '优惠券名称',
					unresize: 'false',
					width: '20%',
					templet: '#couponName'
				}, {
					title: '优惠内容',
					unresize: 'false',
					width: '20%',
					templet: function(data){
						return data.at_least > 0 ? '满' +data.at_least+ '减' +data.money : '无门槛，减' +data.money
					}
				},{
					field: 'gift_state',
					title: '有效期限',
					unresize: 'false',
					width: '30%',
					templet: function (res) {
						if(res.validity_type == 0){
							return "有效时间至" + ns.time_to_date(res.end_time);
						}else{
							return "有效时间" + res.fixed_term + "天";
						}
					}
				}, {
					title: '操作',
					toolbar: '#couponOperation',
					unresize: 'false',
					align: 'center',
					width: '20%'
				}]
			]
		});

		couponTable.tool(function(obj) {
			var data = obj.data;
			switch (obj.event) {
				case "add":
					addcoupon(data);
					break;
			}
		});

		function addcoupon(data){

			var template = `<tr data-coupon="{{ d.platformcoupon_type_id }}">
				<td>{{ d.platformcoupon_name }}</td>
				{{# if(d.at_least > 0){  }}
					<td>满{{ d.at_least }}{{ '减' + d.money }}</td>
				{{# } else { }}
					<td>无门槛，{{'减' + d.money }}</td>
				{{# } }}
				<td style="text-align:center;"><a href="javascript:;" onclick="deleteCoupon(this)" class="ns-text-color">删除</a></td>
			</tr>`;
			laytpl(template).render(data, function(string){
				$(event).parents('.discount-cont').find('.layui-table tbody').append(string);
				layer.closeAll();
			});
			getCoupon();
		}
	})
	// 删除优惠券
	function deleteCoupon(e){
		$(e).parents('tr').remove();
		getCoupon();
	}
	getCoupon();
	//获取已选中优惠券
	function getCoupon() {
		var coupon = [];

		$('.coupon').find('tr[data-coupon]').each(function (i, e) {
			coupon.push($(e).attr('data-coupon'));
		})

		coupon_list = coupon.toString();
	}
    //添加付费规则
	function addRule() {
		let level_select = {:json_encode($level_time, JSON_UNESCAPED_UNICODE)};;
    	$('#level-rule tr').each(function (i, e) {
    		if($(e).find('select').val() && $(e).find('select').val() != undefined){
				delete level_select[$(e).find('select').val()];
			}
		})

    	var select_html = '';
    	for (let i in level_select){
			select_html += '<option value="'+i+'">'+level_select[i]+'</option>';
		}

		var html = `
			<tr>
				<td>
					<div class="ns-len-short">
						<select lay-filter="selectRule">
							${select_html}
						</select>
					</div>
				</td>
				<td class="align-center">
					<input  type="text" value="0" lay-verify="num" class="layui-input ns-len-short price" placeholder="价格/元">
				</td>
				<!--<td class="align-center">
					<input  type="text" value="0" lay-verify="num" class="layui-input ns-len-short market_price" placeholder="划线价/元">
				</td>-->
				<td>
					<a href="javascript:void(0)" class="ns-text-color" onclick="deleteRule(this)">删除</a>
				</td>
			</tr>
		`;

    	$('#level-rule tbody').append(html);
    	if($('#level-rule tr').length == 5){
    		$('#add_rule_btn').hide()
		}
		form.render();
		form.on('select(selectRule)', function(data){
			let num = 0;
			$('#level-rule tr').each(function (i, e) {
				if($(e).find('select').val() == data.value){
					num++;
					$('.delete-rule').removeClass('delete-rule');
					$(e).find('select').addClass('delete-rule');
				}
			})
			if(num > 1) deleteRule($('.delete-rule'));
		});

		form.verify({
			num: function (value) {
				var arrmen = value.split(".");
				var val = 0;
				if (arrmen.length == 2) {
					val = arrmen[1];
				}

				if (value == "") {
					return false;
				}
				if (value < 0 || val.length > 2) {
					return '请输入大于等于0的数，保留小数点后两位'
				}
			}
		})

		return false;
	}


	function deleteRule(obj) {
		$(obj).parents('tr').remove();
		if($('#level-rule tr').length < 5){
			$('#add_rule_btn').show()
		}
	}

</script>

{/block}